package cn.iocoder.yudao.module.reading.controller.app.plan;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.reading.controller.app.plan.vo.ReadingPlanCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.plan.vo.ReadingPlanRespVO;
import cn.iocoder.yudao.module.reading.controller.app.plan.vo.PlanDailyTaskRespVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.plan.PlanDailyTaskDO;
import cn.iocoder.yudao.module.reading.service.plan.PlanDailyTaskService;
import cn.iocoder.yudao.module.reading.convert.plan.ReadingPlanConvert;
import cn.iocoder.yudao.module.reading.dal.dataobject.plan.ReadingPlanDO;
import cn.iocoder.yudao.module.reading.service.plan.ReadingPlanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户 APP - 阅读计划
 *
 * @author 芋道源码
 */
@Tag(name = "用户 APP - 阅读计划")
@RestController
@RequestMapping("/reading/reading-plans")
@Validated
@Slf4j
public class ReadingPlanController {

    @Resource
    private ReadingPlanService readingPlanService;
    @Resource
    private PlanDailyTaskService planDailyTaskService;

    @PostMapping("/create")
    @Operation(summary = "创建阅读计划")
    @PreAuthenticated
    public CommonResult<Long> createReadingPlan(@Valid @RequestBody ReadingPlanCreateReqVO createReqVO) {
        Long userId = getLoginUserId();
        Long planId = readingPlanService.createReadingPlan(userId, createReqVO);
        return success(planId);
    }

    @GetMapping("/list")
    @Operation(summary = "获得用户阅读计划列表")
    @PreAuthenticated
    public CommonResult<List<ReadingPlanRespVO>> getReadingPlanList(
            @Parameter(description = "计划状态", example = "active") @RequestParam(value = "status", required = false) String status) {
        Long userId = getLoginUserId();
        List<ReadingPlanDO> list = readingPlanService.getReadingPlansByUserId(userId, status);
        return success(ReadingPlanConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获得阅读计划详情")
    @PreAuthenticated
    public CommonResult<ReadingPlanRespVO> getReadingPlan(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id) {
        ReadingPlanDO plan = readingPlanService.getReadingPlan(id);
        return success(ReadingPlanConvert.INSTANCE.convert(plan));
    }

    @PutMapping("/{id}/pause")
    @Operation(summary = "暂停阅读计划")
    @PreAuthenticated
    public CommonResult<Boolean> pausePlan(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id) {
        readingPlanService.pausePlan(id);
        return success(true);
    }

    @PutMapping("/{id}/resume")
    @Operation(summary = "恢复阅读计划")
    @PreAuthenticated
    public CommonResult<Boolean> resumePlan(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id) {
        readingPlanService.resumePlan(id);
        return success(true);
    }

    @PutMapping("/{id}/complete")
    @Operation(summary = "完成阅读计划")
    @PreAuthenticated
    public CommonResult<Boolean> completePlan(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id) {
        readingPlanService.completePlan(id);
        return success(true);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除阅读计划")
    @PreAuthenticated
    public CommonResult<Boolean> deletePlan(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id) {
        readingPlanService.deletePlan(id); // 执行物理删除
        return success(true);
    }

    @GetMapping("/{id}/tasks")
    @Operation(summary = "获取计划任务列表")
    @PreAuthenticated
    public CommonResult<List<PlanDailyTaskRespVO>> getPlanTasks(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id,
            @Parameter(description = "任务日期", example = "1") @RequestParam(value = "day", required = false) Integer day,
            @Parameter(description = "任务状态", example = "pending") @RequestParam(value = "status", required = false) String status) {

        List<PlanDailyTaskDO> tasks;

        // 根据参数获取任务列表
        if (day != null) {
            // 如果指定了天数，获取指定日期的任务
            ReadingPlanDO plan = readingPlanService.getReadingPlan(id);
            LocalDate taskDate = plan.getStartDate().plusDays(day - 1);
            tasks = planDailyTaskService.getTasksByPlanIdAndDate(id, taskDate);
        } else {
            // 否则获取所有任务
            tasks = planDailyTaskService.getTasksByPlanId(id, status);
        }

        // 转换为响应VO
        List<PlanDailyTaskRespVO> respVOList = planDailyTaskService.convertToRespVO(tasks);

        return success(respVOList);
    }

    @GetMapping("/{id}/today-tasks")
    @Operation(summary = "获取今日任务")
    @PreAuthenticated
    public CommonResult<List<PlanDailyTaskRespVO>> getTodayTasks(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("id") Long id) {
        // 获取计划信息
        ReadingPlanDO plan = readingPlanService.getReadingPlan(id);

        // 获取今天的任务
        LocalDate today = LocalDate.now();
        List<PlanDailyTaskDO> tasks = planDailyTaskService.getTasksByPlanIdAndDate(id, today);

        // 转换为响应VO
        List<PlanDailyTaskRespVO> respVOList = planDailyTaskService.convertToRespVO(tasks);

        return success(respVOList);
    }

    @GetMapping("/{planId}/book/{bookId}/task-status")
    @Operation(summary = "获取绘本任务状态（调试用）")
    @PreAuthenticated
    public CommonResult<List<PlanDailyTaskRespVO>> getBookTaskStatus(
            @Parameter(description = "计划编号", required = true, example = "1024") @PathVariable("planId") Long planId,
            @Parameter(description = "绘本编号", required = true, example = "181") @PathVariable("bookId") Long bookId) {

        // 获取绘本的所有任务状态
        List<PlanDailyTaskDO> tasks = planDailyTaskService.getTaskStatusByBookId(planId, bookId);

        // 转换为响应VO
        List<PlanDailyTaskRespVO> respVOList = planDailyTaskService.convertToRespVO(tasks);

        return success(respVOList);
    }

    @PostMapping("/tasks/{taskId}/complete")
    @Operation(summary = "完成任务")
    @PreAuthenticated
    public CommonResult<Boolean> completeTask(
            @Parameter(description = "任务ID", required = true, example = "1") @PathVariable("taskId") Long taskId,
            @Parameter(description = "阅读时长（秒）", example = "300") @RequestParam(value = "readingTime", required = false) Integer readingTime,
            @Parameter(description = "备注", example = "这本书很有趣") @RequestParam(value = "notes", required = false) String notes) {

        planDailyTaskService.completeTask(taskId, readingTime, notes);
        return success(true);
    }

    @PostMapping("/tasks/{taskId}/skip")
    @Operation(summary = "跳过任务")
    @PreAuthenticated
    public CommonResult<Boolean> skipTask(
            @Parameter(description = "任务ID", required = true, example = "1") @PathVariable("taskId") Long taskId,
            @Parameter(description = "跳过原因", example = "今天没时间") @RequestParam(value = "reason", required = false) String reason) {

        planDailyTaskService.skipTask(taskId, reason);
        return success(true);
    }

    @PostMapping("/tasks/{taskId}/reset")
    @Operation(summary = "重置任务")
    @PreAuthenticated
    public CommonResult<Boolean> resetTask(
            @Parameter(description = "任务ID", required = true, example = "1") @PathVariable("taskId") Long taskId) {

        planDailyTaskService.resetTask(taskId);
        return success(true);
    }

}
